package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 2020-11-04 11:55
 *
 * https://leetcode-cn.com/problems/trapping-rain-water/
 */
public class _42_接雨水01 {

    public int trap(int[] height) {

        if (height == null || height.length <= 2) {

            return 0;
        }


        int left = 0, right = height.length - 1;

        while (right > 0 && height[right - 1] >= height[right] ) {

            right--;
        }

        if (right == 1) {

            return 0;
        }

        while (left < height.length - 1 && height[left] <= height[left + 1] ) {

            left++;
        }

        if (left == height.length - 1) {

            return 0;
        }

        int index = 0,sum = 0;

        while (left < right) {

            boolean flag = (height[left] < height[right]);

            if (flag) {

                index = left + 1;
            }else {

                index = right- 1;
            }

            if (index == left || index == right) {

                break;
            }
            if (flag) {

                while (height[index] <= height[left] && index < right) {

                    sum += (height[left] - height[index]);
                    index++;
                }

                left = index;
            }else {

                while (height[index] <= height[right] && index > left) {

                    sum += (height[right] - height[index]);
                    index--;
                }

                right = index;
            }
        }

        return sum;
    }
}
